
<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.query" placeholder="请输入关键词" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <!-- <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
      </el-select> -->
      <!-- <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select> -->
      <!-- <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select> -->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查找成员
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加成员
      </el-button>
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        Export
      </el-button> -->
      <!-- <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        reviewer
      </el-checkbox> -->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="头像" prop="img" width="80" align="center">
        <template slot-scope="{row}">
          <img :src="'http://'+row.img" alt="无" width="60px" height="60px">
        </template>
      </el-table-column>
      <el-table-column label="姓名" prop="name" align="center" />
      <el-table-column label="学号" prop="account" align="center" />
      <el-table-column label="角色" prop="roleName" align="center" />
      <el-table-column label="性别" prop="sexName" align="center" />
      <el-table-column label="邮箱" prop="email" align="center" />
      <el-table-column label="手机号" prop="phone" align="center" />
      <el-table-column label="创建时间" prop="createTime" align="center" />
      <el-table-column label="修改时间" prop="updateTime" align="center" />

      <el-table-column label="操作" align="center" min-width="150" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" @click="handleChangeState(row)">
            禁用
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 底部分页组件 -->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <!-- 添加用户弹窗 -->
    <el-dialog v-if="dialogStatus=='create'" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="80px">
        <el-form-item label="注册秘钥" prop="logon">
          <el-input v-model="temp.logon" placeholder="此处填写注册秘钥" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" placeholder="此处填写姓名" />
        </el-form-item>
        <el-form-item label="学号" prop="account">
          <el-input v-model="temp.account" placeholder="此处填写学号" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-radio-group v-model="temp.role">
            <el-radio
              v-for="(item,key,index) in roleObj"
              :key="index"
              :label="key"
            >
              {{ item }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="temp.sex">
            <el-radio
              v-for="(item,key,index) in sexObj"
              :key="index"
              :label="key"
            >
              {{ item }}
            </el-radio>
          </el-radio-group>
          <!-- <el-input v-model="temp.sex" placeholder="此处填写学号" /> -->
          <!-- <el-radio v-model="temp.sex" label="1">男</el-radio>
          <el-radio v-model="temp.sex" label="2">女</el-radio>
          <el-radio v-model="temp.sex" label="0">保密</el-radio> -->
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="temp.password" placeholder="此处填写密码" show-password />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" placeholder="此处填写邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="temp.phone" placeholder="此处填写手机号" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog v-if="dialogStatus=='update'" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="editrules" :model="temp" label-position="right" label-width="80px">

        <el-form-item label="ID" prop="id">
          <el-input v-model="temp.id" placeholder="此处填写ID" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="temp.nickName" placeholder="此处填写昵称" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" placeholder="此处填写姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="temp.sex" :label="1">男</el-radio>
          <el-radio v-model="temp.sex" :label="2">女</el-radio>
          <el-radio v-model="temp.sex" :label="0">保密</el-radio>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="temp.password" placeholder="此处填写新密码" type="password" show-password />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-radio v-model="temp.role" :label="2">普通用户</el-radio>
          <el-radio v-model="temp.role" :label="4">管理员</el-radio>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" placeholder="此处填写邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="temp.phone" placeholder="此处填写手机号" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <!-- <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog> -->

    <!--页脚-->
    <!-- <el-footer class="footer">
      版权所有 &copy; xxxxxxxx &nbsp;&nbsp;
    </el-footer> -->
  </div>
</template>

<script>
import { fetchList, createArticle, updateArticle, deleteArticle } from '@/api/employee'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
// import data from '../pdf/content'

// const calendarTypeOptions = [
//   { key: 'CN', display_name: 'China' },
//   { key: 'US', display_name: 'USA' },
//   { key: 'JP', display_name: 'Japan' },
//   { key: 'EU', display_name: 'Eurozone' }
// ]

// arr to obj, such as { CN : "China", US : "USA" }
// const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
//   acc[cur.key] = cur.display_name
//   return acc
// }, {})

export default {
  name: 'Employee',
  components: { Pagination },
  directives: { waves },
  filters: {
    // 状态显示转换
    // statusFilter(status) {
    //   const statusMap = {
    //     published: 'success',
    //     draft: 'info',
    //     deleted: 'danger'
    //   }
    //   return statusMap[status]
    // },
    // dateFilter: function(data, format = '') {
    //   var dt = new Date(data)
    //   var y = dt.getFullYear()
    //   var m = (dt.getMonth() + 1).toString().padStart(2, '0')
    //   var d = dt.getDate().toString().padStart(2, '0')
    //   var h = dt.getHours().toString().padStart(2, '0')
    //   var mm = dt.getMinutes().toString().padStart(2, '0')
    //   var s = dt.getSeconds().toString().padStart(2, '0')
    //   if (format.toLocaleLowerCase() === 'yyyy-mm-dd' ||
    //         format.toLocaleLowerCase() === '') {
    //     return `${y}-${m}-${d}`
    //   } else if (format.toLocaleLowerCase() === 'yyyy/mm/dd') {
    //     return `${y}/${m}/${d}`
    //   } else if (format.toLocaleLowerCase() === 'yyyy-mm-dd hh:mm:ss') {
    //     return `${y}-${m}-${d} ${h}:${mm}:${s}`
    //   } else if (format.toLocaleLowerCase() === 'yyyy/mm/dd hh:mm:ss') {
    //     return `${y}/${m}/${d} ${h}:${mm}:${s}`
    //   } else {
    //     return `输入的时间格式有误`
    //   }
    // }
  },
  data() {
    // //转换成时间戳
    // row.updateTime = new Date().getTime();
    // console.log('date:'+row.updateTime)

    return {
      tableKey: 0,
      list: [{
        id: '',
        name: '',
        account: '',
        role: '',
        roleName: '',
        sex: '',
        sexName: '',
        email: '',
        phone: '',
        createTime: '',
        updateTime: '',
        img: '',
        nickName: '',
        password: '',
        state: '',
        stateName: ''
      }],
      total: 0,
      listLoading: true,
      // 搜索框请求数据及分页数据
      listQuery: {
        page: 1,
        pageSize: 10,
        state: 1,
        role: '',
        query: ''
      },
      // importanceOptions: [1, 2, 3],
      // calendarTypeOptions,
      // sortOptions: [{ label: 'TIME Ascending', key: '+createTime' }, { label: 'TIME Descending', key: '-createTime' }],
      // statusOptions: ['published', 'draft', 'deleted'],
      // showReviewer: false,
      // 新增与修改界面使用的缓存数据
      temp: {
        logon: '',
        id: '',
        nickName: '',
        name: '',
        sex: '',
        sexName: '',
        password: '',
        account: '',
        img: '',
        role: '',
        roleName: '',
        state: '',
        stateName: '',
        email: '',
        phone: '',
        createTime: '',
        updateTime: ''
      },

      // sexArr:['男','女','保密'],

      roleObj: {
        2: '普通用户',
        4: '管理员'
      },
      sexObj: {
        0: '保密',
        1: '男',
        2: '女'
      },

      // 添加弹窗
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改信息',
        create: '添加成员'
      },
      // dialogPvVisible: false,
      // pvData: [],
      //  type 与上面form表单中的 prop一一对应  required是否必须 message 校验出错时提示的数据
      //  trigger: 'change' 当数据发现变化时触发校验   trigger: 'blur' 当失去焦点时触发校验
      rules: {
        logon: [{ required: true, message: '此处不能为空！', trigger: 'blur' }],
        name: [{ required: true, message: '此处不能为空！', trigger: 'blur' }],
        account: [{ required: true, message: '此处不能为空！', trigger: 'blur' }],
        password: [{ required: true, message: '此处不能为空！', trigger: 'blur' }
          // { pattern: /^{6,32}$/, message: '长度为 6 - 32位' }
        ],
        role: [{ required: true, message: '此处不能为空！', trigger: 'change' }],
        sex: [{ required: true, message: '此处不能为空！', trigger: 'change' }]
      },
      editrules: {
        password: [{ required: false, min: 6, max: 32, message: '密码必须在6-32位之间', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },

  // computed: {
  //   changeDate() {
  //     console.log('time:' + row.updateTime)
  //     return this.temp.updateTime = new Date().getTime()
  //   }
  // },

  // 钩子函数，当界面创建的时候调用.getList() 获取列表数据
  created() {
    this.$nextTick(this.getList())
  },
  methods: {

    // sortByDate(obj1, obj2) {
    //   // var changeTime1 = Number(new Date(this.row.createTime))
    //   // var changeTime2 = Number(new Date(this.row.createTime))
    //   var val1 = obj1.Number(new Date(this.row.createTime))
    //   var val2 = obj2.Number(new Date(this.row.createTime))
    //   return val1 - val2
    // },

    // changeTime() {
    //   var changeTime = Number(new Date(createTime))
    //   console.log('time:' + changeTime)
    // },

    getList() {
      this.listLoading = true
      // 获取表格数据
      fetchList(this.listQuery).then(response => {
        if (response.resultCode === 200) {
          this.list = response.data.list
          this.total = response.data.count
          this.listLoading = false
        }
      })
      if (this.listLoading) {
        setTimeout(() => {
          this.listLoading = false
        }, 2000)
      }
    },
    // 似乎是查找过滤器
    handleFilter() {
      this.listQuery.page = 1
      this.listQuery.pageSize = 10
      this.getList()
    },
    // 似乎是用来改变状态的，控制状态是draft还是publish（草稿或发布）
    // handleModifyStatus(row, status) {
    //   this.$message({
    //     message: '操作Success',
    //     type: 'success'
    //   })
    //   row.status = status
    // },
    // 改变排序的 一开始就绑定在成员列表里了,调用下面的sortByID
    // sortChange(data) {
    //   const { prop, order } = data
    //   if (prop === 'createTime') {
    //     this.sortByID(order)
    //   }
    // },
    // 按id排序，递增或递减
    // sortByID(order) {
    //   if (order === 'ascending') {
    //     this.listQuery.sort = '+createTime'
    //   } else {
    //     this.listQuery.sort = '-createTime'
    //   }
    //   this.handleFilter()
    // },
    // 重置temp缓存数据 在每次点击新增和修改时调用，避免数据出错
    resetTemp() {
      this.temp = {
        id: '',
        nickName: '',
        name: '',
        sex: '',
        sexName: '',
        password: '',
        account: '',
        img: '',
        role: '',
        roleName: '',
        state: '',
        stateName: '',
        email: '',
        phone: '',
        createTime: '',
        updateTime: ''
      }
    },
    // 点击新增按钮触发的方法  展示新增界面
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    // 增删改函数
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 调用增加用户接口
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '添加成功！',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新修改数据
    updateData() {
      console.log('确认', this.temp)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = {
            id: this.temp.id,
            name: this.temp.name,
            sex: this.temp.sex,
            password: this.temp.password,
            img: this.temp.img,
            role: this.temp.role,
            state: this.temp.state,
            email: this.temp.email,
            phone: this.temp.phone
          }
          updateArticle(tempData).then(response => {
            if (response.resultCode === 200) {
              this.getList()
              // const index = this.list.findIndex(v => v.id === this.temp.id)
              // this.list.splice(index, 1, this.temp)// 从index的位置开始更新1个元素
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    // 绑定删除事件，删除表格当前这行
    // handleDelete(row, index) {
    //   deleteArticle(row.id).then(res => {
    //     if (res.resultCode == 200) {
    //       this.$notify({
    //         title: '提示',
    //         message: '删除成功！',
    //         type: 'success',
    //         duration: 2000
    //       })
    //     }
    //     // resetTemp()
    //   }).catch(err => {
    //     console.log(err)
    //   })
    //   this.list.splice(index, 1)
    // },
    // 用户注销/激活（改变用户状态）
    handleChangeState(row) {
      deleteArticle(row.id).then(res => {
        if (res.resultCode === 200) {
          this.$notify({
            title: '提示',
            message: '禁用成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        }
      })
    }

    // handleFetchPv(pv) {
    //   fetchPv(pv).then(response => {
    //     this.pvData = response.data.pvData
    //     this.dialogPvVisible = true
    //   })
    // },

    // 下载？导出成excel？
    // handleDownload() {
    //   this.downloadLoading = true
    //   import('@/vendor/Export2Excel').then(excel => {
    //     const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
    //     const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
    //     const data = this.formatJson(filterVal)
    //     excel.export_json_to_excel({
    //       header: tHeader,
    //       data,
    //       filename: 'table-list'
    //     })
    //     this.downloadLoading = false
    //   })
    // },

    // 时间控件
    // formatJson(filterVal) {
    //   return this.list.map(v => filterVal.map(j => {
    //     if (j === 'timestamp') {
    //       return parseTime(v[j])
    //     } else {
    //       return v[j]
    //     }
    //   }))
    // },
    // getSortClass: function(key) {
    //   const sort = this.listQuery.sort
    //   return sort === `+${key}` ? 'ascending' : 'descending'
    // }
  }
}
</script>

<style lang="scss">
  .footer {
    background-color: #ecf5ff;
    color: black;
    margin: 0;
    position:absolute; /* 必要 */
    bottom:0; /* 必要 */
    width: 100%;
  }
  .el-dialog__wrapper{
    min-width: 1100px;
  }
  .el-form-item__content{
    margin-right: 10%;
  }
  .el-radio{
    margin-top: 9px;
  }
</style>

<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.query" placeholder="请输入关键词" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <!-- <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
      </el-select> -->
      <!-- <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select> -->
      <!-- <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select> -->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查找成员
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加成员
      </el-button>
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        Export
      </el-button> -->
      <!-- <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        reviewer
      </el-checkbox> -->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%">
      <el-table-column label="头像" prop="img" width="80" align="center">
          <template slot-scope="{row}">
            <img :src="'http://'+row.img" alt="无" width="60px" height="60px">
          </template>
      </el-table-column>
      <el-table-column label="姓名" prop="name" align="center"/>
      <el-table-column label="学号" prop="account" align="center"/>
      <el-table-column label="角色" prop="roleName" align="center"/>
      <el-table-column label="性别" prop="sexName" align="center"/>
      <el-table-column label="邮箱" prop="email" align="center"/>
      <el-table-column label="手机号" prop="phone" align="center"/>
      <el-table-column label="创建时间" prop="createTime" align="center"/>
      <el-table-column label="修改时间" prop="updateTime" align="center"/>

      <el-table-column label="操作" align="center" min-width="150" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" @click="handleChangeState(row)">
            禁用
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 底部分页组件 -->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <!-- 添加用户弹窗 -->
    <el-dialog v-if="dialogStatus=='create'" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" placeholder="此处填写姓名" />
        </el-form-item>
        <el-form-item label="学号" prop="account">
          <el-input v-model="temp.account" placeholder="此处填写学号" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-radio-group v-model="temp.role">
            <el-radio
              v-for="(item,key,index) in roleObj"
              :key="index"
              :label="key"
            >
              {{ item }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="temp.sex">
            <el-radio
              v-for="(item,key,index) in sexObj"
              :key="index"
              :label="key"
            >
              {{ item }}
            </el-radio>
          </el-radio-group>
          <!-- <el-input v-model="temp.sex" placeholder="此处填写学号" /> -->
          <!-- <el-radio v-model="temp.sex" label="1">男</el-radio>
          <el-radio v-model="temp.sex" label="2">女</el-radio>
          <el-radio v-model="temp.sex" label="0">保密</el-radio> -->
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="temp.password" placeholder="此处填写密码" show-password />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" placeholder="此处填写邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="temp.phone" placeholder="此处填写手机号" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog v-if="dialogStatus=='update'" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="editrules" :model="temp" label-position="right" label-width="80px">

        <el-form-item label="ID" prop="id">
          <el-input v-model="temp.id" placeholder="此处填写ID" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="temp.nickName" placeholder="此处填写昵称" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" placeholder="此处填写姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="temp.sex" :label="1">男</el-radio>
          <el-radio v-model="temp.sex" :label="2">女</el-radio>
          <el-radio v-model="temp.sex" :label="0">保密</el-radio>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="temp.password" placeholder="此处填写新密码" type="password" show-password />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-radio v-model="temp.role" :label="2">普通用户</el-radio>
          <el-radio v-model="temp.role" :label="4">管理员</el-radio>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" placeholder="此处填写邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="temp.phone" placeholder="此处填写手机号" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <!-- <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog> -->

    <!--页脚-->
    <!-- <el-footer class="footer">
      版权所有 &copy; xxxxxxxx &nbsp;&nbsp;
    </el-footer> -->
  </div>
</template>

<script>
import { fetchList, createArticle, updateArticle, deleteArticle } from '@/api/employee'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
// import data from '../pdf/content'

// const calendarTypeOptions = [
//   { key: 'CN', display_name: 'China' },
//   { key: 'US', display_name: 'USA' },
//   { key: 'JP', display_name: 'Japan' },
//   { key: 'EU', display_name: 'Eurozone' }
// ]

// arr to obj, such as { CN : "China", US : "USA" }
// const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
//   acc[cur.key] = cur.display_name
//   return acc
// }, {})

export default {
  name: 'Employee',
  components: { Pagination },
  directives: { waves },
  filters: {
    // 状态显示转换
    // statusFilter(status) {
    //   const statusMap = {
    //     published: 'success',
    //     draft: 'info',
    //     deleted: 'danger'
    //   }
    //   return statusMap[status]
    // },
    // dateFilter: function(data, format = '') {
    //   var dt = new Date(data)
    //   var y = dt.getFullYear()
    //   var m = (dt.getMonth() + 1).toString().padStart(2, '0')
    //   var d = dt.getDate().toString().padStart(2, '0')
    //   var h = dt.getHours().toString().padStart(2, '0')
    //   var mm = dt.getMinutes().toString().padStart(2, '0')
    //   var s = dt.getSeconds().toString().padStart(2, '0')
    //   if (format.toLocaleLowerCase() === 'yyyy-mm-dd' ||
    //         format.toLocaleLowerCase() === '') {
    //     return `${y}-${m}-${d}`
    //   } else if (format.toLocaleLowerCase() === 'yyyy/mm/dd') {
    //     return `${y}/${m}/${d}`
    //   } else if (format.toLocaleLowerCase() === 'yyyy-mm-dd hh:mm:ss') {
    //     return `${y}-${m}-${d} ${h}:${mm}:${s}`
    //   } else if (format.toLocaleLowerCase() === 'yyyy/mm/dd hh:mm:ss') {
    //     return `${y}/${m}/${d} ${h}:${mm}:${s}`
    //   } else {
    //     return `输入的时间格式有误`
    //   }
    // }
  },
  data() {
    // //转换成时间戳
    // row.updateTime = new Date().getTime();
    // console.log('date:'+row.updateTime)

    return {
      tableKey: 0,
      list: [{
        id: '',
        name: '',
        account: '',
        role: '',
        roleName: '',
        sex: '',
        sexName: '',
        email: '',
        phone: '',
        createTime: '',
        updateTime: '',
        img: '',
        nickName: '',
        password: '',
        state: '',
        stateName: ''
      }],
      total: 0,
      listLoading: true,
      // 搜索框请求数据及分页数据
      listQuery: {
        page: 1,
        pageSize: 10,
        state: 1,
        role: '',
        query: ''
      },
      // importanceOptions: [1, 2, 3],
      // calendarTypeOptions,
      // sortOptions: [{ label: 'TIME Ascending', key: '+createTime' }, { label: 'TIME Descending', key: '-createTime' }],
      // statusOptions: ['published', 'draft', 'deleted'],
      // showReviewer: false,
      // 新增与修改界面使用的缓存数据
      temp: {
        id: '',
        nickName: '',
        name: '',
        sex: '',
        sexName: '',
        password: '',
        account: '',
        img: '',
        role: '',
        roleName: '',
        state: '',
        stateName: '',
        email: '',
        phone: '',
        createTime: '',
        updateTime: ''
      },

      // sexArr:['男','女','保密'],

      roleObj: {
        2: '普通用户',
        4: '管理员'
      },
      sexObj: {
        0: '保密',
        1: '男',
        2: '女'
      },

      // 添加弹窗
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改信息',
        create: '添加成员'
      },
      // dialogPvVisible: false,
      // pvData: [],
      //  type 与上面form表单中的 prop一一对应  required是否必须 message 校验出错时提示的数据
      //  trigger: 'change' 当数据发现变化时触发校验   trigger: 'blur' 当失去焦点时触发校验
      rules: {
        name: [{ required: true, message: '此处不能为空！', trigger: 'blur' }],
        account: [{ required: true, message: '此处不能为空！', trigger: 'blur' }],
        password: [{ required: true, message: '此处不能为空！', trigger: 'blur' }
          // { pattern: /^{6,32}$/, message: '长度为 6 - 32位' }
        ],
        role: [{ required: true, message: '此处不能为空！', trigger: 'change' }],
        sex: [{ required: true, message: '此处不能为空！', trigger: 'change' }]
      },
      editrules: {
        password: [{ required: false, min: 6, max: 32, message: '密码必须在6-32位之间', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },

  // computed: {
  //   changeDate() {
  //     console.log('time:' + row.updateTime)
  //     return this.temp.updateTime = new Date().getTime()
  //   }
  // },

  // 钩子函数，当界面创建的时候调用.getList() 获取列表数据
  created() {
    this.$nextTick(this.getList())
  },
  methods: {

    // sortByDate(obj1, obj2) {
    //   // var changeTime1 = Number(new Date(this.row.createTime))
    //   // var changeTime2 = Number(new Date(this.row.createTime))
    //   var val1 = obj1.Number(new Date(this.row.createTime))
    //   var val2 = obj2.Number(new Date(this.row.createTime))
    //   return val1 - val2
    // },

    // changeTime() {
    //   var changeTime = Number(new Date(createTime))
    //   console.log('time:' + changeTime)
    // },

    getList() {
      this.listLoading = true
      // 获取表格数据
      fetchList(this.listQuery).then(response => {
        if(response.resultCode === 200) {
          this.list = response.data.list
          this.total = response.data.count
          this.listLoading = false
        }
      })
      if (this.listLoading) {
        setTimeout(() => {
          this.listLoading = false
        }, 2000)
      }
    },
    // 似乎是查找过滤器
    handleFilter() {
      this.listQuery.page = 1
      this.listQuery.pageSize = 10
      this.getList()
    },
    // 似乎是用来改变状态的，控制状态是draft还是publish（草稿或发布）
    // handleModifyStatus(row, status) {
    //   this.$message({
    //     message: '操作Success',
    //     type: 'success'
    //   })
    //   row.status = status
    // },
    // 改变排序的 一开始就绑定在成员列表里了,调用下面的sortByID
    // sortChange(data) {
    //   const { prop, order } = data
    //   if (prop === 'createTime') {
    //     this.sortByID(order)
    //   }
    // },
    // 按id排序，递增或递减
    // sortByID(order) {
    //   if (order === 'ascending') {
    //     this.listQuery.sort = '+createTime'
    //   } else {
    //     this.listQuery.sort = '-createTime'
    //   }
    //   this.handleFilter()
    // },
    // 重置temp缓存数据 在每次点击新增和修改时调用，避免数据出错
    resetTemp() {
      this.temp = {
        id: '',
        nickName: '',
        name: '',
        sex: '',
        sexName: '',
        password: '',
        account: '',
        img: '',
        role: '',
        roleName: '',
        state: '',
        stateName: '',
        email: '',
        phone: '',
        createTime: '',
        updateTime: ''
      }
    },
    // 点击新增按钮触发的方法  展示新增界面
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    // 增删改函数
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 调用增加用户接口
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '添加成功！',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新修改数据
    updateData() {
      console.log('确认', this.temp)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = {
            id: this.temp.id,
            name: this.temp.name,
            sex: this.temp.sex,
            password: this.temp.password,
            img: this.temp.img,
            role: this.temp.role,
            state: this.temp.state,
            email: this.temp.email,
            phone: this.temp.phone
          }
          updateArticle(tempData).then(response => {
            if (response.resultCode === 200) {
              this.getList()
              // const index = this.list.findIndex(v => v.id === this.temp.id)
              // this.list.splice(index, 1, this.temp)// 从index的位置开始更新1个元素
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    // 绑定删除事件，删除表格当前这行
    // handleDelete(row, index) {
    //   deleteArticle(row.id).then(res => {
    //     if (res.resultCode == 200) {
    //       this.$notify({
    //         title: '提示',
    //         message: '删除成功！',
    //         type: 'success',
    //         duration: 2000
    //       })
    //     }
    //     // resetTemp()
    //   }).catch(err => {
    //     console.log(err)
    //   })
    //   this.list.splice(index, 1)
    // },
    // 用户注销/激活（改变用户状态）
    handleChangeState(row) {
      deleteArticle(row.id).then(res => {
        if (res.resultCode === 200) {
          this.$notify({
            title: '提示',
            message: '禁用成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        }
      })
    },

    // handleFetchPv(pv) {
    //   fetchPv(pv).then(response => {
    //     this.pvData = response.data.pvData
    //     this.dialogPvVisible = true
    //   })
    // },

    // 下载？导出成excel？
    // handleDownload() {
    //   this.downloadLoading = true
    //   import('@/vendor/Export2Excel').then(excel => {
    //     const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
    //     const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
    //     const data = this.formatJson(filterVal)
    //     excel.export_json_to_excel({
    //       header: tHeader,
    //       data,
    //       filename: 'table-list'
    //     })
    //     this.downloadLoading = false
    //   })
    // },

    // 时间控件
    // formatJson(filterVal) {
    //   return this.list.map(v => filterVal.map(j => {
    //     if (j === 'timestamp') {
    //       return parseTime(v[j])
    //     } else {
    //       return v[j]
    //     }
    //   }))
    // },
    // getSortClass: function(key) {
    //   const sort = this.listQuery.sort
    //   return sort === `+${key}` ? 'ascending' : 'descending'
    // }
  }
}
</script>

<style lang="scss">
  .footer {
    background-color: #ecf5ff;
    color: black;
    margin: 0;
    position:absolute; /* 必要 */
    bottom:0; /* 必要 */
    width: 100%;
  }
  .el-dialog__wrapper{
    min-width: 1100px;
  }
  .el-form-item__content{
    margin-right: 10%;
  }
  .el-radio{
    margin-top: 9px;
  }
</style>

